﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Common.Core.HttpHandler
{
    public class AjaxHandlerFactory : IHttpHandlerFactory
    {
        /// <summary>
        /// 缓存，用于缓存请求的Ajax实例
        /// </summary>
        private System.Web.Caching.Cache _cache = HttpContext.Current.Cache;
        /// <summary>
        /// 用参数类名(ClassName)返回ajax业务类
        /// </summary>
        /// <param name="strUrlPath"></param>
        /// <returns></returns>
        private string GetClassName(string strUrlPath)
        {
            return System.Text.RegularExpressions.Regex.Replace(strUrlPath, @"/\w+/(\w+).fxd", "Common.Facade.HttpHandler.$1, Common.Facade");
        }
        #region IHttpHandlerFactory 成员

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            string strClass = context.Request.Path;
            if (string.IsNullOrEmpty(strClass)) return null;
            string strClassName = GetClassName(strClass);
            //优先从缓存中获取实例
            object handle = _cache.Get(strClassName);
            if (handle != null)
            {
                return (IHttpHandler)handle;
            }

            Type t = Type.GetType(strClassName, false, true);
            if (t != null)
            {
                if (t.GetInterface("IHttpHandler", true) != null)
                {
                    return (IHttpHandler)Activator.CreateInstance(t);
                }
            }
            return null;
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            //如果handle不为null，且设置了IsReusable为true，则缓存handle
            if (handler != null && handler.IsReusable)
            {
                string className = handler.GetType().FullName.ToUpper();
                _cache.Insert(className, handler, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));
            }
        }

        #endregion
    }
}
